package org.example.game.weekly.game440;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author wyatt
 * @Data 2024/08/03 20:46
 */
public class Solution002 {

    public static void main(String[] args) {
        System.out.println(new Solution002().findMaxSum(new int[]{4,2,1,5,3}, new int[]{10,20,30,40,50}, 2).length);
    }


    /**
     * @Description:
     * 从最小开始加
     * 如果累计数字不足K, 加数据
     * 如果累计数字大于K，替换1个最小数字， 重排序
     *
     * @auther: wyatt
     * @date: 11:00 2025/3/9
    */

    public long[] findMaxSum(int[] nums1, int[] nums2, int k) {

        int[] findMax = new int[k];
        Arrays.fill(findMax, 0);

        Map<Integer, List<Integer>> numToIndexListMap = new HashMap<>();

        for (int i = 0; i < nums1.length; i++) {
            numToIndexListMap.putIfAbsent(nums1[i], new ArrayList<>());
            numToIndexListMap.get(nums1[i]).add(i);
        }

        Map<Integer, Integer> indexValueMap = new HashMap<>();
        for (int i = 0; i < nums2.length; i++) {
            indexValueMap.put(i, nums2[i]);
        }

        int[] sortNums1 = nums1;
        Arrays.sort(sortNums1);
        long[] res = new long[nums1.length];

        List<Integer> sortedList = Arrays.stream(nums1)
                .boxed()
                .sorted().distinct()
                .collect(Collectors.toList());

        long sum = 0;
        for (int i = 0; i < sortedList.size(); i++) {

            List<Integer> indexList = numToIndexListMap.get(sortedList.get(i));
            if(i == 0){
                for (int j = 0; j < indexList.size(); j++) {
                    res[indexList.get(j)] = 0;
                }
            }else {
                for (int j = 0; j < indexList.size(); j++) {
                    res[indexList.get(j)] = sum;
                }
            }

            for (int j = 0; j < indexList.size(); j++) {
                int indexValue = indexValueMap.get(indexList.get(j));
                sum = fillMax(sum, findMax, indexValue);
            }
        }

        return res;
    }

    private long fillMax(long sum, int[] findMax, int indexValue) {
        if(indexValue > findMax[0]){
            sum += indexValue;
            sum -= findMax[0];
            findMax[0] = indexValue;
            for (int i = 1; i < findMax.length; i++) {
                if(findMax[i] < findMax[i-1]){
                    int value = findMax[i];
                    findMax[i] = findMax[i-1];
                    findMax[i-1] = value;
                }else {
                    break;
                }
            }
        }
        return sum;
    }


}
